package com.guomei.controller.exam;

import com.guomei.bean.curse.AddOrUpdateExam;
import com.guomei.bean.exam.domain.Exam;
import com.guomei.bean.exam.vo.UserExamRequest;
import com.guomei.constans.ExamCode;
import com.guomei.service.curse.UserCourseLearnService;
import com.guomei.service.exam.ExamService;
import com.guomei.utils.JwtUtil;
import com.guomei.utils.Result;
import com.guomei.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 考试控制器
 */
@RestController
@RequestMapping("/api1/exam")
@Slf4j
public class ExamController {
    @Autowired
    private ExamService examService;
    
    @Autowired
    private UserCourseLearnService userCourseLearnService;


     /**
     * 获取考试信息
     * @return 考试列表
     */
    @PostMapping("/select")
    public Result<?> getAllExams(@RequestBody Exam exam) {
        log.info("获取考试信息");
        try {
            if (exam == null || exam.getPageNum() == null || exam.getPageSize() == null) {
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (exam.getPageNum() <= 0 || exam.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            return examService.getByCondition(exam);
        } catch (Exception e) {
            log.info("获取考试信息失败", e);
            return Result.fail("获取考试信息失败");
        }
    }
    
    /**
     * 获取用户考试信息（需要课程学习进度达到80%）
     * @param dto 查询参数
     * @return 考试列表
     */
    @PostMapping("/selectUserExam")
    public Result<?> getAllUserExams(@RequestBody com.guomei.bean.exam.vo.SelectUserExamDTO dto) {
        log.info("获取用户可参加的考试信息: userId={}", dto != null ? dto.getUserId() : null);
        try {
            // 参数校验
            if (dto == null) {
                return Result.fail("请求参数不能为空");
            }
            if (dto.getUserId() == null) {
                return Result.fail("用户ID不能为空");
            }
            if (dto.getPageNum() == null || dto.getPageSize() == null) {
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (dto.getPageNum() <= 0 || dto.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            
            // 调用service方法，获取用户可参加的考试（学习进度达到80%）
            return examService.getUserQualifiedExams(dto.getUserId(), dto.getPageNum(), dto.getPageSize());
        } catch (Exception e) {
            log.error("获取用户考试信息失败", e);
            return Result.fail("获取考试信息失败: " + e.getMessage());
        }
    }


    /**
     * 根据ID获取考试详情
     * @param id 考试ID
     * @return 考试详情
     */
    @GetMapping("/detail/{id}")
    public Result<?> getExamDetail(@PathVariable Long id) {
        log.info("获取考试详情，ID：{}", id);
        try {
            if (id == null) {
                return Result.fail("考试ID不能为空");
            }
            Exam exam = examService.getById(id);
            if (exam == null) {
                return Result.fail("考试不存在");
            }
            return Result.success(exam);
        } catch (Exception e) {
            log.info("获取考试详情失败", e);
            return Result.fail("获取考试详情失败");
        }
    }

    /**
     * 创建/修改考试
     * @param addOrUpdateExam 考试信息
     * @return 创建/修改结果
     */
    @PostMapping("/addExam")
    public Result<?> createExam(@Valid @RequestBody AddOrUpdateExam addOrUpdateExam, BindingResult result) {
        log.info("创建/修改考试入参：{}", addOrUpdateExam);
        //实体类注解参数校验
        Result<?> commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        Exam exam = new Exam();
        exam.setExamName(addOrUpdateExam.getExamName());
        exam.setCourseId(addOrUpdateExam.getCourseId());
        exam.setCoverImage(addOrUpdateExam.getCoverImage());
        exam.setDescription(addOrUpdateExam.getDescription());
        exam.setExamType(addOrUpdateExam.getExamType());
        exam.setDuration(addOrUpdateExam.getDuration());
        exam.setPrice(addOrUpdateExam.getPrice());
        exam.setStartTime(addOrUpdateExam.getStartTime());
        exam.setEndTime(addOrUpdateExam.getEndTime());
        exam.setCreatorId(addOrUpdateExam.getCreatorId());
        exam.setCreatedTime(addOrUpdateExam.getCreatedTime());
        exam.setUpdatedTime(addOrUpdateExam.getUpdatedTime());
        try {
            if (addOrUpdateExam.getId() == null) {
                log.info("进行创建考试处理");
                exam.setStatus((short) ExamCode.UNPUBLISHED.getCode());
                boolean success = examService.save(exam);
                return success ? Result.success("处理成功") : Result.fail("处理失败");
            } else {
                log.info("进行修改考试处理");
                exam.setStatus(addOrUpdateExam.getStatus());
                exam.setId(addOrUpdateExam.getId());
                boolean success = examService.update(exam);
                return success ? Result.success("处理成功") : Result.fail("处理失败");
            }
        } catch (Exception e) {
            log.info("创建/修改考试处理失败", e);
            return Result.error("处理失败");
        }
    }

    /**
     * 删除考试
     * @param id 考试ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public Result<?> deleteExam(@PathVariable Long id) {
        log.info("删除考试，ID：{}", id);
        try {
            if (id == null) {
                return Result.fail("考试ID不能为空");
            }
            boolean success = examService.removeById(id);
            return success ? Result.success("删除成功") : Result.fail("删除失败");
        } catch (Exception e) {
            log.info("删除考试失败", e);
            return Result.fail("删除考试失败");
        }
    }

    /**
     * 根据课程ID获取考试列表
     * @param courseId 课程ID
     * @return 考试列表
     */
    @GetMapping("/course/{courseId}")
    public Result<?> getExamsByCourseId(@PathVariable Long courseId) {
        log.info("根据课程ID获取考试列表，课程ID：{}", courseId);
        try {
            if (courseId == null) {
                return Result.fail("课程ID不能为空");
            }
            return Result.success(examService.getByCourseId(courseId));
        } catch (Exception e) {
            log.info("根据课程ID获取考试列表失败", e);
            return Result.fail("获取考试列表失败");
        }
    }

    /**
     * 根据创建人ID获取考试列表
     * @param creatorId 创建人ID
     * @return 考试列表
     */
    @GetMapping("/creator/{creatorId}")
    public Result<?> getExamsByCreatorId(@PathVariable Long creatorId) {
        log.info("根据创建人ID获取考试列表，创建人ID：{}", creatorId);
        try {
            if (creatorId == null) {
                return Result.fail("创建人ID不能为空");
            }
            return Result.success(examService.getByCreatorId(creatorId));
        } catch (Exception e) {
            log.info("根据创建人ID获取考试列表失败", e);
            return Result.fail("获取考试列表失败");
        }
    }

    /**
     * 根据状态获取考试列表
     * @param status 状态
     * @return 考试列表
     */
    @GetMapping("/status/{status}")
    public Result<?> getExamsByStatus(@PathVariable Short status) {
        log.info("根据状态获取考试列表，状态：{}", status);
        try {
            if (status == null) {
                return Result.fail("状态不能为空");
            }
            return Result.success(examService.getByStatus(status));
        } catch (Exception e) {
            log.info("根据状态获取考试列表失败", e);
            return Result.fail("获取考试列表失败");
        }
    }


    /**
     * 根据examID 获取考试详情
     * @param examId 考试ID
     * @return 考试详情
     */
    @GetMapping("/exam/{examId}")
    public Result<?> getExamDetailByExamId(@PathVariable Long examId) {
        log.info("根据考试ID获取考试详情，考试ID：{}", examId);
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            return Result.success(examService.getByIdWithQuestions(examId));
        } catch (Exception e) {
            log.info("根据考试ID获取考试详情失败", e);
            return Result.fail("获取考试详情失败");
        }
    }
    /** 
     * 根据用户的 token，获取用户购买的课程对应的考试
    */
    @PostMapping("/user/exams")
    public Result<?> getExamsByUserToken(@RequestHeader("Authorization") String tokenString, @RequestBody UserExamRequest userExamRequest) {
        log.info("根据用户的 token，获取用户购买的课程对应的考试，token：{}, 分页参数：{}", tokenString, userExamRequest);

        try {
            // 验证分页参数
            if (userExamRequest == null) {
                return Result.fail("请求参数不能为空");
            }
            if (userExamRequest.getPageNum() == null || userExamRequest.getPageSize() == null) {
                return Result.fail("分页参数不能为空");
            }
            if (userExamRequest.getPageNum() <= 0 || userExamRequest.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }

            // 从Authorization header中提取token（去掉Bearer前缀）
            String token = tokenString;
            if (tokenString.startsWith("Bearer ")) {
                token = tokenString.substring(7);
            }
            
            // 从token中获取用户ID
            Long userId = JwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return Result.fail("无效的token");
            }
            
            // 获取用户学习的课程ID列表
            List<Long> courseIds = userCourseLearnService.getCourseIdsByUserId(userId);
            
            // 根据课程ID列表查询考试（分页）
            return examService.getByCourseIdsWithPage(courseIds, userExamRequest.getPageNum(), userExamRequest.getPageSize());
            
        } catch (Exception e) {
            log.error("根据用户的 token，获取用户购买的课程对应的考试失败", e);
            return Result.fail("获取考试列表失败");
        }
    }
}
